package com.bop.dehong.lock;

import android.app.Dialog;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.base.dehong.util.LogUtils;
import com.base.dehong.util.PreferencesUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.BaseActivity;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.config.Config;
import com.bop.dehong.gesturepwd.GestureContentView;
import com.bop.dehong.gesturepwd.GestureDrawline.GestureCallBack;
import com.bop.dehong.gesturepwd.LockIndicator;
import com.bop.dehong.login.LoginActivity;
/**
 * 手势密码
 * @author TangWenhan/YeFengyun
 * 2015年12月2日上午10:48:33
 */
public class GesturePwdActivity extends BaseActivity
{
//    private LocusPassWordView lpwv;
    private String password;
    private boolean from_set;
    
    //后面添加
    private LockIndicator mLockIndicator;
    private TextView top_bar_left_txt;
	private TextView mTextTip;
	private TextView mTitleTv, mTitle2Tv, mForgetPwd;
	private FrameLayout mGestureContainer;
	private GestureContentView mGestureContentView;
	private boolean mIsFirstInput = true;
	private String mFirstPassword = null;
	private String mConfirmPassword = null;
	private int mParamIntentCode;
	private int mCount = 0;
	
	boolean RESET_PSW;
	//设置三种类型，验证，设置，重新设置
	private int mAction_Type = 0;
	
	private final int VERIFY_ACTION = 0;
	private final int SET_ACTION = 1;
	private final int RESET_ACTION = 2;
	private String mOriginalPwdStr = "";
	private boolean isVerify = false;
	private boolean goBack = false, showForgetPwd = true;

	@Override
	protected void initTop() {
		Intent intent = getIntent();
		goBack = intent.getBooleanExtra(Config.GO_BACK, false);
		if (intent.hasExtra("isshow")) {
			showForgetPwd = intent.getBooleanExtra("isshow", false);
		}else {
			showForgetPwd =  PreferencesUtils.getBoolean(
					this, Config.isNoFirstIn);
		}
		mAction_Type = intent.getIntExtra(Config.GESTURE_ACTION, 0);
		top_bar_left_txt = getView(R.id.top_bar_left_txt);
		if (mAction_Type != 0) {
			top_bar_left_txt.setVisibility(View.VISIBLE);
		}else {
			top_bar_left_txt.setVisibility(View.GONE);
		}
	}

	@Override
	protected void initUI() {
		mLockIndicator =getView(R.id.lock_indicator);
		mGestureContainer = getView(R.id.gesture_container);
		mTextTip = getView(R.id.text_tip);
		mTitleTv = getView(R.id.title);
		mTitle2Tv = getView(R.id.title_2);
		mForgetPwd = getView(R.id.forget_pwd);
		registerOnClickListener(top_bar_left_txt, mForgetPwd);
		
		if (mAction_Type == SET_ACTION) {
			mTitleTv.setVisibility(View.VISIBLE);
			mTitle2Tv.setText("为了您的账户安全，请设置手势密码图案");
			if (showForgetPwd) {
				mForgetPwd.setVisibility(View.VISIBLE);
			}else {
				mForgetPwd.setVisibility(View.GONE);
			}
		}else if (mAction_Type == VERIFY_ACTION) {
			mTitle2Tv.setText("请输入手势密码");
			String name = PreferencesUtils.getString(this, Config.USERNAME);
			mOriginalPwdStr = PreferencesUtils.getString(this, Config.GESTURE_PWD+name);
			isVerify = true;
			LogUtils.e(TAG + "mOriginalPwdStr" + mOriginalPwdStr);
		}else if (mAction_Type == RESET_ACTION) {
			mTitleTv.setVisibility(View.VISIBLE);
			mTitleTv.setText("修改手势密码");
//			mTitle2Tv.setVisibility(View.INVISIBLE);
			mTitle2Tv.setText("输入原密码");
			mForgetPwd.setVisibility(View.INVISIBLE);
			String name = PreferencesUtils.getString(this, Config.USERNAME);
			mOriginalPwdStr = PreferencesUtils.getString(this, Config.GESTURE_PWD+name);
			isVerify = true;
		}
		
		initGestureView();
	}
	private void initGestureView(){
		mGestureContentView = new GestureContentView(this, isVerify, mOriginalPwdStr, gestureCallback);
		
		// 设置手势解锁显示到哪个布局里面
		mGestureContentView.setParentView(mGestureContainer);
		updateCodeList("");
	}
	
	GestureCallBack gestureCallback = new GestureCallBack() {
		
		@Override
		public void onGestureCodeInput(String inputCode) {
			LogUtils.e(TAG + ", gesture", "inputCode:"+inputCode);
			if (!isInputPassValidate(inputCode)) {
				mTextTip.setText(Html.fromHtml("<font color='#ff4343'>最少链接4个点, 请重新输入</font>"));
				mGestureContentView.clearDrawlineState(0L);
				return;
			}
			//验证密码，只需要一次
			if(mAction_Type == VERIFY_ACTION){
//				verifyCode(inputCode);
			}else if(mAction_Type == SET_ACTION){//设置
				setPwd(inputCode);
			}else {//重新设置 ,这个就分两部，前面的验证加上后面的设置
//				resetPwd(inputCode);
			}
		}
		
		@Override
		public void checkedSuccess(String inputCode) {
			updateCodeList(inputCode);
			mTextTip.setText("绘制解锁图案");
			mGestureContentView.clearDrawlineState(0L);
			if (mAction_Type == VERIFY_ACTION) {
				setResult(RESULT_OK);
				finishCurrentActivity();
			}else if (mAction_Type == RESET_ACTION) {
				resetPwd();
			}
			
			
		}
		
		@Override
		public void checkedFail(String inputCode) {
			updateCodeList(inputCode);
			mGestureContentView.clearDrawlineState(1300L);
			mCount++;
			if (mCount >= 5) {
				mTextTip.setText(Html
						.fromHtml("<font color='#FE7F2E'>密码错误</font>"));
				showReLoginDialog();
			}else{
				mGestureContentView.clearDrawlineState(1300L);
				mTextTip.setText(Html
						.fromHtml("<font color='#FE7F2E'>密码错误，还有"+(5-mCount)+"次机会</font>"));
			}
			// 左右移动动画
			Animation shakeAnimation = AnimationUtils.loadAnimation(GesturePwdActivity.this, R.anim.shake);
			mTextTip.startAnimation(shakeAnimation);
		}
	};
	/**
	 * 验证手势密码
	 * @param inputCode
	 */
//	private void verifyCode(String inputCode){
//		updateCodeList(inputCode);
//		//OK
//		setResult(RESULT_OK);
//		this.finish();
//	}
	private void setPwd(String inputCode){
		if (mIsFirstInput) {
			mFirstPassword = inputCode;
			mTitle2Tv.setText("再次输入新密码");
			updateCodeList(inputCode);
			mGestureContentView.clearDrawlineState(0L);
		} else {
			if (inputCode.equals(mFirstPassword)) {
					Toast.makeText(GesturePwdActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
				mGestureContentView.clearDrawlineState(0L);
				
				String name = PreferencesUtils.getString(this, Config.USERNAME);
				PreferencesUtils.putString(this, Config.GESTURE_PWD + name, inputCode);
				
				setResult(RESULT_OK);
				this.finish();
			} else {
				mTextTip.setText(Html.fromHtml("<font color='#cc3432'>与上一次绘制不一致，请重新绘制</font>"));
				// 左右移动动画
				Animation shakeAnimation = AnimationUtils.loadAnimation(GesturePwdActivity.this, R.anim.shake);
				mTextTip.startAnimation(shakeAnimation);
				// 保持绘制的线，1.5秒后清除
				mGestureContentView.clearDrawlineState(1300L);
			}
		}
		mIsFirstInput = false;
	}
	private void resetPwd(){
		mOriginalPwdStr = "";
		mGestureContainer.removeAllViews();
		mAction_Type = SET_ACTION;
		isVerify = false;
		mTitle2Tv.setText("输入新密码");
		initGestureView();
		
	}
	private boolean isInputPassValidate(String inputPassword) {
		if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) {
			return false;
		}
		return true;
	}
	
	/*
	 * 更新选择的图
	 */
	private void updateCodeList(String inputCode) {
		mLockIndicator.setPath(inputCode);
	}
	
	Dialog mLoginDialog;
	private void  showReLoginDialog() {
		mLoginDialog = new Dialog(this, R.style.MyDialogStyle);
		View view = View.inflate(this, R.layout.dialog_re_login, null);
		mLoginDialog.setContentView(view);
		mLoginDialog.setCancelable(false);
		Button loginBtn = getView(view, R.id.re_login);
		registerOnClickListener(loginBtn);
		mLoginDialog.show();
	}
	Dialog mForgetPwdDialog;
	private void showForgetDialog(){
		mForgetPwdDialog = new Dialog(this, R.style.MyDialogStyle);
		View view = View.inflate(this, R.layout.dialog_forget_pwd, null);
		mForgetPwdDialog.setContentView(view);
		mForgetPwdDialog.setCancelable(false);
		Button loginBtn = getView(view, R.id.re_login);
		Button forget = getView(view, R.id.re_cancel);
		registerOnClickListener(loginBtn,forget);
		mForgetPwdDialog.show();
	}
	
	@Override
		protected void onDestroy() {
			super.onDestroy();
			if (mLoginDialog!= null) {
				mLoginDialog.dismiss();
				mLoginDialog = null;
			}
			if (mForgetPwdDialog != null) {
				mForgetPwdDialog.dismiss();
				mForgetPwdDialog = null;
			}
		}

	@Override
	protected void initData() {
	        RESET_PSW = PreferencesUtils.getBoolean(this, Config.RESET_PSW);
	        if(RESET_PSW){
	        	PreferencesUtils.putBoolean(
						this, Config.RESET_PSW, false);
	        }
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                 && event.getRepeatCount() == 0) {
        	if (goBack) {
        		if (mAction_Type != 0) {
    				finishCurrentActivity();
    			}else {
    				finishActivity(101);
    				finishCurrentActivity();
    			} 	
        	}
        	return true;
         }
         return super.onKeyDown(keyCode, event);
     }

	@Override
	protected int getContentViewId() {
		TAG = getClass().getName();
		return R.layout.activity_set_password;
	}

//	@Override
//	public void uponClick(View v) {
//		switch (v.getId()) {
//		case R.id.top_bar_left_txt:
//			if (goBack) {
//				finishCurrentActivity();
//			}
//			break;
//		case R.id.re_login:
//			if (mLoginDialog!= null) {
//				mLoginDialog.dismiss();
//				mLoginDialog = null;
//			}
//			if (mForgetPwdDialog!= null) {
//				mForgetPwdDialog.dismiss();
//				mForgetPwdDialog = null;
//			}
//			String name = PreferencesUtils.getString(this, Config.USERNAME);
//			PreferencesUtils.remove(this, Config.GESTURE_PWD+name);//删除手势密码，记住，这里上删除上一个人的手势密码
//			PreferencesUtils.remove(this, Config.PASSWORD);
//			if (DeHongApp.mLoginEntity != null) {
//				DeHongApp.mLoginEntity = null;
//			}
//			finishAllActivity();//删除所有的Activity
//			Intent intent = new Intent(this, LoginActivity.class);
//			intent.putExtra("go2main", true);
//			startActivity(intent);
//			break;
//		case R.id.forget_pwd:
//			showForgetDialog();
//			break;
//		case R.id.re_cancel:
//			if (mForgetPwdDialog!= null) {
//				mForgetPwdDialog.dismiss();
//				mForgetPwdDialog = null;
//			}
//			break;
//		default:
//			break;
//		}
//	}
//
//	@Override
//	public void uponItemClick(AdapterView<?> arg0, View arg1, int arg2,
//			long arg3) {
//		// TODO Auto-generated method stub
//		
//	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.top_bar_left_txt:
			if (goBack) {
				finishCurrentActivity();
			}
			break;
		case R.id.re_login:
			if (mLoginDialog!= null) {
				mLoginDialog.dismiss();
				mLoginDialog = null;
			}
			if (mForgetPwdDialog!= null) {
				mForgetPwdDialog.dismiss();
				mForgetPwdDialog = null;
			}
			String name = PreferencesUtils.getString(this, Config.USERNAME);
			PreferencesUtils.remove(this, Config.GESTURE_PWD+name);//删除手势密码，记住，这里上删除上一个人的手势密码
			PreferencesUtils.remove(this, Config.PASSWORD);
			if (DeHongApp.mLoginEntity != null) {
				DeHongApp.mLoginEntity = null;
			}
			finishAllActivity();//删除所有的Activity
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra("go2main", true);
			startActivity(intent);
			break;
		case R.id.forget_pwd:
			showForgetDialog();
			break;
		case R.id.re_cancel:
			if (mForgetPwdDialog!= null) {
				mForgetPwdDialog.dismiss();
				mForgetPwdDialog = null;
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}
}
